import React, { useEffect, useState } from 'react';
import { useStaticState, useTRState } from '#/utils/trHooks.jsx';
import styles from '../planPage/index.less';
import { Checkbox, Col, Input, Radio, Row, Select, Space, Tooltip, message } from 'antd';
import DealUnit from '../../components/dealUnit';
import { features, useTablePipeline } from 'ali-react-table';
import tacticDeleteLineSvg from '@/assets/InterprovincialSpotDeclaration/tactic_delete_line.svg';
import TacticPage from '../../plan/tacticPage';
import { TjTable } from '@/pages/ETrade/components';
import { PlusSquareOutlined, QuestionCircleOutlined } from '#/utils/antdIcons';
import {
  ELECTRIC_ENERGY_OPTIONS,
  ELECTRIC_PRICE_OPTIONS,
  TOOLTIP_INFO,
  unitStyle,
} from '../../constant';
import { PeriodPicker } from '../../components/periodPicker';
import {
  buildDataKey,
  buildStationObjByData,
  buildTimeFrameArrTatic2,
  changePrice,
  disabledDate,
  getHourOrder,
  getOptionsByHourOrder,
  getPercent,
  getThreeDecimal,
  getTimePointByValue,
  getTimesPoint,
  stringToArray,
  tableStyle,
  TimeFrameArr,
} from '../../helper';
import { connect } from 'umi';
import _ from 'lodash';
import DatePickerMultiple from '../../components/DatePickerMultiple';

const inputStyle = { width: 64, height: 24, fontSize: 12, padding: 3 };

const { Option } = Select;

const tooltipStyle = { color: 'rgba(253, 79, 67, 1)', marginLeft: 5 };

const Tactic2 = ({
  strategyData = {},
  endOrder,
  planData,
  index,
  activeKey,
  type,
  selectRowsObj,
  dispatch,
  disabled,
}) => {
  const [showAddBtn, setShowAddBtn] = useState(false);
  const staticData = useStaticState({
    addDataSource: [],
  });

  // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
  const [checkDisabled, setCheckDisabled] = useState(false);

  useEffect(() => {
    // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
    if (strategyData.electricEnergy === 1) {
      let data = _.cloneDeep(planData);
      if (type === 'intraday') {
        data[+activeKey].strategyList[index].details?.forEach((i) => {
          i?.children?.forEach((j) => {
            j.electricType = 1;
            j.electric1 = 100;
          });
        });
      } else {
        data[+activeKey].strategyList[index].details?.forEach((i) => {
          i.electricType = 1;
          i.electric1 = 100;
        });
      }
      dispatch({
        type: 'interprovincialSpotDeclaration/setState',
        payload: {
          planData: data,
        },
      });
      setCheckDisabled(true);
    } else {
      setCheckDisabled(false);
    }
  }, [strategyData.electricEnergy]);

  useEffect(() => {
    if (type === 'dayahead') {
      // 日前的情况策略2表格长度不能超过96条
      const length = strategyData?.details?.length || 0;
      setShowAddBtn(length < 96);
    } else {
      // 日内的情况策略2表格长度不能超过8条
      const length = strategyData?.details?.length || 0;
      setShowAddBtn(length < 8);
    }
  }, [strategyData]);

  const changeInfoData = (v, key, rowKey) => {
    let data = _.cloneDeep(planData);
    if (type === 'intraday') {
      const indexArr = stringToArray(rowKey);
      const faIndex = indexArr?.[0] || 0;
      const sonIndex = indexArr?.[1] || 0;
      data[+activeKey].strategyList[index].details[faIndex]['children'][sonIndex][key] = v;
    } else {
      data[+activeKey].strategyList[index].details[rowKey][key] = v;
    }
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };

  const deleteRow = (rowKey) => {
    const data = _.cloneDeep(planData);
    let arr = _.cloneDeep(data[+activeKey].strategyList[index].details);
    arr?.splice(rowKey, 1);
    arr = buildDataKey(arr);
    data[+activeKey].strategyList[index].details = arr;
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };

  const changeOrderData = (v, key, rowKey) => {
    let data = _.cloneDeep(planData);
    let timePeriod;
    let indexArr;
    let faIndex;
    let sonIndex;
    if (type === 'intraday') {
      indexArr = rowKey.slice('-');
      faIndex = Number(indexArr?.[0] || 0);
      sonIndex = Number(indexArr?.[2] || 0);
      timePeriod = strategyData?.details?.[faIndex]['children'][sonIndex]['timePeriod'] || '';
    } else {
      timePeriod = strategyData?.details?.[rowKey]['timePeriod'] || '';
    }
    timePeriod = timePeriod.split('-');
    if (key === 'startOrder') {
      timePeriod[0] = v;
    } else {
      timePeriod[1] = v;
    }
    if (type === 'intraday') {
      data[+activeKey].strategyList[index].details[faIndex]['children'][sonIndex][key] = v;
      data[+activeKey].strategyList[index].details[faIndex]['children'][sonIndex]['timePeriod'] =
        timePeriod?.join('-');
    } else {
      data[+activeKey].strategyList[index].details[rowKey][key] = v;
      data[+activeKey].strategyList[index].details[rowKey]['timePeriod'] = timePeriod?.join('-');
    }
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };

  const changeOrderDataTimePlan = (v, key, rowKey) => {
    let data = _.cloneDeep(planData);
    let timePeriod;
    let indexArr;
    let faIndex;
    let sonIndex;

    if (!strategyData?.details) return;

    if (type === 'intraday') {
      indexArr = rowKey.split('-');

      faIndex = Number(indexArr?.[0] || 0);
      sonIndex = Number(indexArr?.[1] || 0);

      const faDetails = strategyData?.details?.[faIndex];

      if (!faDetails?.children?.[sonIndex]) return;

      // timePeriod = strategyData?.details?.[faIndex]['children'][sonIndex]['timePeriod'] || '';
      timePeriod = faDetails.children[sonIndex].timePeriod || '';
    } else {
      timePeriod = strategyData?.details?.[rowKey]['timePeriod'] || '';
    }
    timePeriod = timePeriod.split('-');
    if (key === 'startOrder') {
      timePeriod[0] = v;
    } else {
      timePeriod[1] = v;
    }
    if (type === 'intraday') {
      data[+activeKey].strategyList[index].details[faIndex]['children'][sonIndex][key] = v;
      data[+activeKey].strategyList[index].details[faIndex]['children'][sonIndex]['timePeriod'] =
        timePeriod?.join('-');
    } else {
      data[+activeKey].strategyList[index].details[rowKey][key] = v;
      data[+activeKey].strategyList[index].details[rowKey]['timePeriod'] = timePeriod?.join('-');
    }
    // staticData.addDataSource = data[+activeKey].strategyList[index].details;
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };

  const columns = [
    {
      code: 'timePeriod',
      name: '时间段',
      align: 'center',
      width: 130,
      render: (v, record) => {
        const startTimeValue = getTimesPoint(record.startOrder);
        const endTimeValue = getTimesPoint(record.endOrder);
        const faHourOrder = getHourOrder(strategyData.details, record);
        const options = getOptionsByHourOrder(faHourOrder);
        return record.disabled ? (
          record.startOrder + '-' + record.endOrder
        ) : (
          <PeriodPicker
            options={options}
            type={type}
            disabled={disabled}
            list={strategyData.details || []}
            startTimeValue={startTimeValue}
            endTimeValue={endTimeValue}
            onChange={(v, key) => changeOrderData(v, key, record.key)}
          />
        );
      },
    },
    {
      name: '电力',
      align: 'center',
      children: [
        {
          name: (
            <>
              <span>比例</span>
              <span style={unitStyle}>(%)</span>
            </>
          ),
          code: 'proportion',
          align: 'center',
          render: (_, record) => {
            if (record.disabled) {
              return <></>;
            } else {
              const isChecked = record.electricType === 1;
              return (
                <Radio
                  disabled={disabled || checkDisabled}
                  checked={isChecked}
                  onClick={() => {
                    changeInfoData(1, 'electricType', record.key);
                  }}
                >
                  <Input
                    type={'number'}
                    disabled={!isChecked || disabled || checkDisabled}
                    value={record.electric1}
                    style={inputStyle}
                    onChange={(e) => {
                      const value = getPercent(e.target.value);
                      changeInfoData(value, 'electric1', record.key);
                    }}
                  />
                </Radio>
              );
            }
          },
        },
        {
          name: (
            <>
              <span>固定值</span>
              <span style={unitStyle}>(MW)</span>
            </>
          ),
          code: 'fixedValue',
          align: 'center',
          render: (_, record) => {
            if (record.disabled) {
              return <></>;
            } else {
              const isChecked = record.electricType === 2;
              return (
                <Radio
                  disabled={disabled || checkDisabled}
                  checked={isChecked}
                  onClick={() => {
                    changeInfoData(2, 'electricType', record.key);
                  }}
                >
                  <Input
                    type={'number'}
                    disabled={!isChecked || disabled}
                    value={record.electric2}
                    style={inputStyle}
                    onChange={(e) => {
                      changeInfoData(e.target.value, 'electric2', record.key);
                    }}
                  />
                </Radio>
              );
            }
          },
        },
      ],
    },
    {
      code: 'price',
      features: {
        autoRowSpan: (v1, v2, row1, row2) => {
          return !row1.disabled && !row2.disabled;
        },
      },
      name: (
        <>
          <div>电价</div>
          <div style={unitStyle}>(元/MW)</div>
        </>
      ),
      width: 60,
      align: 'center',
      render: (v, record) =>
        !record.disabled && (
          <Input
            disabled={disabled}
            type={'number'}
            value={v}
            style={{ ...inputStyle, width: '100%' }}
            onChange={(e) => {
              const value = getThreeDecimal(e.target.value);
              changeAllPrice(value, record);
            }}
          />
        ),
    },
    {
      code: 'key',
      name: '',
      align: 'center',
      width: type !== 'intraday' ? 40 : 80,
      render: (v, record) =>
        !disabled &&
        !record.disabled &&
        (type !== 'intraday' ? (
          <img
            src={tacticDeleteLineSvg}
            alt={''}
            style={{ cursor: 'pointer' }}
            onClick={() => deleteRow(v)}
          />
        ) : (
          <Space>
            <a onClick={() => addTableLineChildren(record)}>新增</a>
            <a
              style={{ color: 'rgba(255, 92, 92, 1)' }}
              onClick={() => deleteTableLineChildren(record)}
            >
              删除
            </a>
          </Space>
        )),
    },
  ];

  const columnsTimePlan = [
    {
      code: 'timePeriod',
      name: '时间段',
      align: 'center',
      width: 130,
      render: (v, record) => {
        const startTimeValue = getTimesPoint(record.startOrder);
        const endTimeValue = getTimesPoint(record.endOrder);
        const faHourOrder = getHourOrder(strategyData.details, record);
        const options = getOptionsByHourOrder(faHourOrder);
        return record.disabled ? (
          record.startOrder + '-' + record.endOrder
        ) : (
          <PeriodPicker
            options={options}
            type={type}
            disabled={disabled}
            list={strategyData.details || []}
            startTimeValue={startTimeValue}
            endTimeValue={endTimeValue}
            onChange={(v, key) => changeOrderDataTimePlan(v, key, record.key)}
          />
        );
      },
    },
    {
      name: '电力',
      align: 'center',
      children: [
        {
          name: (
            <>
              <span>比例</span>
              <span style={unitStyle}>(%)</span>
            </>
          ),
          code: 'proportion',
          align: 'center',
          render: (_, record) => {
            if (record.disabled) {
              return <></>;
            } else {
              const isChecked = record.electricType === 1;
              return (
                <Radio
                  disabled={disabled || checkDisabled}
                  checked={isChecked}
                  onClick={() => {
                    changeInfoData(1, 'electricType', record.key);
                  }}
                >
                  <Input
                    type={'number'}
                    disabled={!isChecked || disabled || checkDisabled}
                    value={record.electric1}
                    style={inputStyle}
                    onChange={(e) => {
                      const value = getPercent(e.target.value);
                      changeInfoData(value, 'electric1', record.key);
                    }}
                  />
                </Radio>
              );
            }
          },
        },
        {
          name: (
            <>
              <span>固定值</span>
              <span style={unitStyle}>(MW)</span>
            </>
          ),
          code: 'fixedValue',
          align: 'center',
          render: (_, record) => {
            if (record.disabled) {
              return <></>;
            } else {
              const isChecked = record.electricType === 2;
              return (
                <Radio
                  disabled={disabled || checkDisabled}
                  checked={isChecked}
                  onClick={() => {
                    changeInfoData(2, 'electricType', record.key);
                  }}
                >
                  <Input
                    type={'number'}
                    disabled={!isChecked || disabled}
                    value={record.electric2}
                    style={inputStyle}
                    onChange={(e) => {
                      changeInfoData(e.target.value, 'electric2', record.key);
                    }}
                  />
                </Radio>
              );
            }
          },
        },
      ],
    },
    {
      code: 'price',
      features: {
        autoRowSpan: (v1, v2, row1, row2) => {
          return !row1.disabled && !row2.disabled;
        },
      },
      name: (
        <>
          <div>电价</div>
          <div style={unitStyle}>(元/MW)</div>
        </>
      ),
      width: 60,
      align: 'center',
      render: (v, record) =>
        !record.disabled && (
          <Input
            disabled={disabled}
            type={'number'}
            value={v}
            style={{ ...inputStyle, width: '100%' }}
            onChange={(e) => {
              const value = getThreeDecimal(e.target.value);
              changeAllPrice(value, record);
            }}
          />
        ),
    },
    {
      code: 'key',
      name: '',
      align: 'center',
      width: type !== 'intraday' ? 40 : 80,
      render: (v, record) => {
        const showAddBtn = type === 'intraday' && record?.level === 2 && isLastChild(record);

        return (
          !disabled &&
          !record.disabled &&
          (type !== 'intraday' ? (
            <img
              src={tacticDeleteLineSvg}
              alt={''}
              style={{ cursor: 'pointer' }}
              onClick={() => deleteRow(v)}
            />
          ) : (
            <Space>
              {/* {showAddBtn && (
                <a onClick={() => addTableLineChildren(record, strategyData?.details)}>新增</a>
              )} */}
              <a
                onClick={
                  showAddBtn ? () => addTableLineChildren(record, strategyData?.details) : undefined
                }
                disabled={!showAddBtn}
              >
                新增
              </a>
              <a
                style={{ color: 'rgba(255, 92, 92, 1)' }}
                onClick={() => deleteTableLineChildren(record)}
              >
                删除
              </a>
            </Space>
          ))
        );
      },
    },
  ];

  const isLastChild = (record) => {
    if (!strategyData?.details?.length || !record?.key) return false;

    const indexArr = stringToArray(record.key);
    const faIndex = indexArr?.[0];
    const sonIndex = indexArr?.[1];

    const parent = strategyData.details[faIndex];
    if (!parent?.children?.length) return false;

    // 检查是否是最后一个子节点
    const isLast = Number(sonIndex) === parent.children.length - 1;

    // 如果是最后一个子节点，还需要检查下一个时间段是否会超出父节点范围
    if (isLast) {
      const lastEndTime = record.endOrder;
      const nextEndTime = getTimesPoint(getTimePointByValue(getTimesPoint(lastEndTime)));
      const faEndTime = getTimesPoint(parent.endOrder);

      // 如果下一个时间段会超出父节点范围，则禁用新增按钮
      return nextEndTime <= faEndTime;
    }

    return false;
  };

  // const isLastChild = (record) => {
  //   if (!strategyData?.details?.length || !record?.key) return false;

  //   const indexArr = stringToArray(record.key);
  //   const faIndex = indexArr?.[0];
  //   const sonIndex = indexArr?.[1];

  //   // if (!faIndex || !sonIndex) return false;

  //   // 判断是否是最后一个父节点
  //   /* const isLastParent = Number(faIndex) === strategyData.details.length - 1;
  //   if (!isLastParent) return false; */

  //   // 判断是否是该父节点的最后一个子节点
  //   const parent = strategyData.details[faIndex];
  //   if (!parent?.children?.length) return false;

  //   return Number(sonIndex) === parent.children.length - 1;
  // };

  const onChangeOpenKeys = (v) => {
    let selectArr = v;
    if (selectArr.toString() === 'root') {
      selectArr = strategyData?.details?.map((i) => i.key) || [];
    }
    const obj = _.cloneDeep(selectRowsObj);
    obj[index] = selectArr;
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        selectRowsObj: obj,
      },
    });
  };

  const pipeline = useTablePipeline({ components: { Checkbox } })
    .input({ dataSource: strategyData.details || [], columns })
    .primaryKey('key')
    .use(
      features.multiSelect({
        value: selectRowsObj[index] || [],
        onChange: onChangeOpenKeys,
      }),
    )
    .use(features.autoRowSpan());

  const disablePipeline = useTablePipeline({ components: {} })
    .input({ dataSource: strategyData.details || [], columns })
    .primaryKey('key')
    .use(features.autoRowSpan());

  const treePipeline = useTablePipeline({ components: { Checkbox } })
    .input({ dataSource: strategyData.details || [], columns: columnsTimePlan })
    .primaryKey('key')
    .use(
      features.treeMode({
        defaultOpenKeys: [0],
      }),
    )
    .use(
      features.treeSelect({
        tree: strategyData.details || [],
        checkboxPlacement: 'start',
        rootKey: 'root',
        onChange: onChangeOpenKeys,
        value: selectRowsObj[index] || [],
        clickArea: 'cell',
        checkboxColumn: { lock: true },
        highlightRowWhenSelected: true,
      }),
    )
    .use(features.autoRowSpan());

  const treeDisablePipeline = useTablePipeline({ components: {} })
    .input({ dataSource: strategyData.details || [], columns })
    .primaryKey('key')
    .use(
      features.treeMode({
        defaultOpenKeys: [0],
      }),
    )
    .use(features.autoRowSpan());

  const changePlanData = (data) => {
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };

  // 日内的情况下，添加子集，最多为八个
  const addTableLineChildren = (v) => {
    const data = _.cloneDeep(planData);
    let arr = _.cloneDeep(
      /* staticData.addDataSource.length > 0 ? staticData.addDataSource :  */ strategyData?.details,
    );

    const indexArr = stringToArray(v.key);
    const faIndex = indexArr?.[0] || 0;
    const faData = arr[faIndex];

    let children = faData['children'] || [];
    let count = children.length + 1;
    if (count > 8) return;

    // 获取上一个子节点的结束时间作为新节点的开始时间
    let lastEndTime =
      children.length > 0 ? children[children.length - 1].endOrder : faData.startOrder;

    const nextEndTime = getTimePointByValue(getTimesPoint(lastEndTime));

    // 校验是否超过父节点结束时间
    const faEndTime = getTimesPoint(faData.endOrder);
    const newEndTime = getTimesPoint(nextEndTime);
    if (newEndTime > faEndTime) {
      return;
    }

    // 检查时间段是否重叠
    const isEndOrderDuplicate = children.reduce((acc, child) => {
      const childEnd = getTimesPoint(child.endOrder);
      acc[childEnd] = (acc[childEnd] || 0) + 1;
      return acc;
    }, {});

    if (Object.values(isEndOrderDuplicate).some((count) => count > 1)) {
      message.warning('结束时间段存在重复，请检查!');
      return;
    }

    const isTimeOverlap = children.some((child) => {
      const childStart = getTimesPoint(child.startOrder);
      const childEnd = getTimesPoint(child.endOrder);
      const newStart = getTimesPoint(lastEndTime);
      const newEnd = newEndTime;

      // 检查条件
      return (
        (newStart >= childStart && newStart < childEnd) || // 新开始时间在已有时间段内
        (newEnd > childStart && newEnd <= childEnd) || // 新结束时间在已有时间段内
        (newStart <= childStart && newEnd >= childEnd) || // 新时间段完全包含已有时间段
        childStart >= childEnd || // 开始时间大于等于结束时间
        childStart === newStart || // 开始时间和结束时间段相同
        childEnd === newEnd
      );
    });

    if (isTimeOverlap) {
      message.warning('时间段有误，请检查!');
      return;
    }

    // 检查时间段是否连续
    /* if (children.length > 0) {
      const lastChild = children[children.length - 1];
      const lastEndPoint = getTimesPoint(lastChild.endOrder);
      const newStartPoint = getTimesPoint(lastEndTime);

      if (newStartPoint !== lastEndPoint) {
        message.warning('时间段必须连续，请检查');
        return;
      }
    } */

    // 创建新子节点
    const newChild = {
      startOrder: lastEndTime,
      endOrder: nextEndTime,
      timePeriod: `${lastEndTime}-${nextEndTime}`,
      electricType: 1,
      level: 2,
      electric1: strategyData.electricEnergy === 1 ? 100 : '',
      price: v?.price || '',
    };

    children.push(newChild);
    arr[faIndex].children = children;
    arr = buildDataKey(arr);
    data[+activeKey].strategyList[index].details = arr;
    // staticData.addDataSource = arr;
    onChangeOpenKeys([]);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };

  // const addTableLineChildren = (v) => {
  //   const data = _.cloneDeep(planData);
  //   let arr = _.cloneDeep(
  //     staticData.addDataSource.length > 0 ? staticData.addDataSource : strategyData?.details,
  //   );

  //   const indexArr = stringToArray(v.key);
  //   const faIndex = indexArr?.[0] || 0;
  //   const faData = arr[faIndex];

  //   // 如果存在children则使用,否则初始化为空数组
  //   let children = faData['children'] || [];
  //   let count = children.length + 1;
  //   if (count > 8) return;

  //   // 获取上一个子节点的结束时间作为新节点的开始时间
  //   let lastEndTime =
  //     children.length > 0 ? children[children.length - 1].endOrder : faData.startOrder;

  //   // 计算新的结束时间
  //   const nextEndTime = getTimePointByValue(getTimesPoint(lastEndTime));

  //   // 校验是否超过父节点结束时间
  //   const faEndTime = getTimesPoint(faData.endOrder);
  //   const newEndTime = getTimesPoint(nextEndTime);

  //   // 如果新的结束时间会超过父节点的结束时间，禁用新增按钮
  //   if (newEndTime > faEndTime) {
  //     return; // 或者可以给出提示
  //     /* message.warning('已达到父节点的结束时间，无法继续添加'); */
  //   }

  //   // 创建新子节点
  //   const newChild = {
  //     startOrder: lastEndTime,
  //     endOrder: nextEndTime,
  //     timePeriod: `${lastEndTime}-${nextEndTime}`,
  //     electricType: 1,
  //     level: 2,
  //     electric1: strategyData.electricEnergy === 1 ? 100 : '',
  //     price: v?.price || '',
  //   };

  //   // 添加到children数组
  //   children.push(newChild);

  //   // 更新父节点的children
  //   arr[faIndex].children = children;

  //   // 重建key
  //   arr = buildDataKey(arr);

  //   // 更新状态
  //   data[+activeKey].strategyList[index].details = arr;
  //   staticData.addDataSource = arr;

  //   onChangeOpenKeys([]);
  //   dispatch({
  //     type: 'interprovincialSpotDeclaration/setState',
  //     payload: {
  //       planData: data,
  //     },
  //   });
  // };

  /*   const addTableLineChildren = (v) => {
    const data = _.cloneDeep(planData);
    // 直接使用 staticData.addDataSource 而不是其长度判断
    let arr = _.cloneDeep(
      staticData.addDataSource.length > 0 ? staticData.addDataSource : strategyData?.details,
    );

    const indexArr = stringToArray(v.key);
    const faIndex = indexArr?.[0] || 0;
    const faData = arr[faIndex];

    // 如果存在children则使用,否则初始化为空数组
    let children = faData['children'] || [];
    let count = children.length + 1;
    if (count > 8) return;

    // 获取上一个子节点的结束时间作为新节点的开始时间
    let lastEndTime =
      children.length > 0 ? children[children.length - 1].endOrder : faData.startOrder;

    // 创建新子节点
    const newChild = {
      startOrder: lastEndTime,
      endOrder: getTimePointByValue(getTimesPoint(lastEndTime)),
      timePeriod: `${lastEndTime}-${getTimePointByValue(getTimesPoint(lastEndTime))}`,
      electricType: 1,
      level: 2,
      electric1: strategyData.electricEnergy === 1 ? 100 : '',
      price: v?.price || '',
    };

    // 添加到children数组
    children.push(newChild);

    // 更新父节点的children
    arr[faIndex].children = children;

    // 重建key
    arr = buildDataKey(arr);

    // 更新状态
    data[+activeKey].strategyList[index].details = arr;
    staticData.addDataSource = arr;

    onChangeOpenKeys([]);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  }; */

  // const addTableLineChildren = (v) => {
  //   const data = _.cloneDeep(planData);
  //   let arr =
  //     staticData.addDataSource.length > 0 ? staticData.addDataSource : strategyData?.details;

  //   const indexArr = stringToArray(v.key);
  //   const faIndex = indexArr?.[0] || 0;
  //   const faData = arr[faIndex];
  //   let children = faData['children'];
  //   let count = children.length + 1;
  //   if (count > 8) return;

  //   const startMin = getTimesPoint(faData.startOrder);
  //   const endMin = getTimesPoint(faData.endOrder);
  //   const total = endMin - startMin;
  //   // const seg = Math.floor(total / count / 15) * 15;
  //   const seg = Math.floor(total / count);

  //   let newChildren = [];
  //   let segStart = startMin;
  //   let firstStart = getTimesPoint(faData.startOrder);
  //   firstStart = getTimePointByValue(firstStart);
  //   for (let i = 0; i < count; i++) {
  //     let segEnd = segStart + 1;
  //     /* if (i === count - 1) {
  //       segEnd = endMin - 1;
  //     } else {
  //       segEnd = segStart + seg;
  //     } */
  //     /* if (i === count - 1) {
  //       segEnd = segStart + 1;
  //     } else {
  //       // segEnd = ;
  //       // 获取上一个时间段的结束时间
  //       if (newChildren.length > 0) {
  //         const lastChild = newChildren[newChildren.length - 1];
  //         segEnd = getTimesPoint(lastChild.endOrder);
  //       } else {
  //         segEnd = segStart + 1;
  //       }
  //     } */
  //     newChildren.push({
  //       startOrder: i === 0 ? firstStart : getTimePointByValue(segStart),
  //       endOrder: getTimePointByValue(segEnd),
  //       timePeriod: `${
  //         i === 0 ? faData.startOrder : getTimePointByValue(segStart)
  //       }-${getTimePointByValue(segEnd)}`,
  //       electricType: 1,
  //       level: 2,
  //       // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
  //       electric1: strategyData.electricEnergy === 1 ? 100 : '',
  //       price: v?.price || '',
  //     });
  //     segStart = segEnd;
  //   }
  //   arr[faIndex]['children'] = newChildren;
  //   arr = buildDataKey(arr);
  //   data[+activeKey].strategyList[index].details = arr;

  //   onChangeOpenKeys([]);
  //   dispatch({
  //     type: 'interprovincialSpotDeclaration/setState',
  //     payload: {
  //       planData: data,
  //     },
  //   });
  // };

  /* const addTableLineChildren = (v) => {
    const data = _.cloneDeep(planData);
    let arr = strategyData?.details;
    const indexArr = stringToArray(v.key);
    const faIndex = indexArr?.[0] || 0;
    if (arr[faIndex]['children'].length === 8) {
      return;
    }
    const faData = arr[faIndex];
    let start = getTimesPoint(faData.startOrder);
    let end = getTimesPoint(faData.endOrder);
    start = getTimePointByValue(start);
    end = getTimePointByValue(end - 1);
    arr[faIndex]['children'].push({
      startOrder: start,
      endOrder: end,
      timePeriod: start + '-' + end,
      electricType: 1,
      level: 2,
      // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
      electric1: strategyData.electricEnergy === 1 ? 100 : '',
      price: v?.price || '',
    });
    arr = buildDataKey(arr);
    data[+activeKey].strategyList[index].details = arr;
    onChangeOpenKeys([]);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  }; */

  // 删除子集，至少存在一个
  const deleteTableLineChildren = (v) => {
    const data = _.cloneDeep(planData);
    let arr = _.cloneDeep(strategyData?.details || []);
    const indexArr = stringToArray(v.key);
    const faIndex = indexArr?.[0] || 0;
    const sonIndex = indexArr?.[1] || 0;

    // 检查是否只剩一个子节点
    if (arr[faIndex]['children'].length === 1) {
      return;
    }

    // 删除指定的子节点
    arr[faIndex]['children'].splice(sonIndex, 1);

    // 重建key
    arr = buildDataKey(arr);

    // 更新状态数据
    data[+activeKey].strategyList[index].details = arr;

    // 同步更新 staticData
    // staticData.addDataSource = arr;
    onChangeOpenKeys([]);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };
  /*   const deleteTableLineChildren = (v) => {
    const data = _.cloneDeep(planData);
    let arr = _.cloneDeep(strategyData?.details || []);
    const indexArr = stringToArray(v.key);
    const faIndex = indexArr?.[0] || 0;
    const sonIndex = indexArr?.[1] || 0;
    if (arr[faIndex]['children'].length === 1) {
      return;
    }
    arr[faIndex]['children'].splice(sonIndex, 1);
    arr = buildDataKey(arr);
    data[+activeKey].strategyList[index].details = arr;
    onChangeOpenKeys([]);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  }; */

  const changeMarkDate = (v) => {
    const markDate = v.toString();
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].markDate = markDate;
    const stationObj = buildStationObjByData(data);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
        stationObj,
      },
    });
  };

  const changeElectricEnergy = (v) => {
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].electricEnergy = v;
    changePlanData(data);
  };

  const changeElectricPriceType = (v) => {
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].electricPriceType = v;
    changePlanData(data);
  };

  const addTableLine = () => {
    const data = _.cloneDeep(planData);
    const arr = data?.[+activeKey]?.strategyList?.[index]?.details || [];
    const price = strategyData?.details?.[0]?.price || '';
    const key = arr.length;
    const obj = {
      timePeriod: '0015-2400',
      startOrder: '0015',
      endOrder: '2400',
      electricType: 1,
      // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
      electric1: strategyData.electricEnergy === 1 ? 100 : '',
      electric2: '',
      price,
      key,
    };
    arr.push(obj);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        planData: data,
      },
    });
  };

  const changeTimeFrame = (v) => {
    const details = strategyData?.details || [];
    let arr = [];
    let timeFrame = buildTimeFrameArrTatic2(v, strategyData);
    timeFrame.forEach((i) => {
      if (details.some((a) => a.timePeriod === i.timePeriod)) {
        const value = details.filter((f) => f.timePeriod === i.timePeriod)?.[0];
        arr.push(value);
      } else {
        arr.push(i);
      }
    });
    arr = buildDataKey(arr);
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index]['hourOrderList'] = v;
    data[+activeKey].strategyList[index].details = arr;
    onChangeOpenKeys([]);
    // staticData.addDataSource = [];
    changePlanData(data);
  };

  const changeElectricPrice = (e) => {
    const value = getThreeDecimal(e.target.value);
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].electricPrice = value;
    data[+activeKey].strategyList[index].details = changePrice(strategyData.details, value);
    changePlanData(data);
  };

  const changeAllPrice = (v, record) => {
    let arr = _.cloneDeep(strategyData?.details || []);
    if (record.level === 2) {
      arr.forEach((i) => {
        if (i?.children?.some((a) => a.timePeriod === record.timePeriod)) {
          i.children.forEach((b) => (b.price = v));
        }
      });
    } else {
      arr = changePrice(arr, v);
    }
    let data = _.cloneDeep(planData);
    data[+activeKey].strategyList[index].details = arr;
    changePlanData(data);
  };

  return (
    <TacticPage title={strategyData.strategyName} index={index} disabled={disabled}>
      {type !== 'intraday' ? (
        <div className={styles.tactic_line_margin}>
          <div className={styles.tactic_line_title_box}>
            <div className={styles.tactic_line_title}>标的日</div>
            <div className={styles.tactic_line_title}>*可多选</div>
          </div>
          <DatePickerMultiple
            disabled={disabled}
            value={strategyData.markDate ? strategyData.markDate.split(',') : []}
            disabledDate={(current) => disabledDate(current, endOrder)}
            onChange={changeMarkDate}
          />
        </div>
      ) : (
        <div className={styles.tactic_line_margin}>
          <div className={styles.tactic_line_title}>时段</div>
          <div style={{ marginBottom: 8 }}>
            <Checkbox
              indeterminate={
                (strategyData?.hourOrderList?.length || 0) > 0 &&
                (strategyData?.hourOrderList?.length || 0) < TimeFrameArr.length
              }
              checked={(strategyData?.hourOrderList?.length || 0) === TimeFrameArr.length}
              disabled={disabled}
              onChange={(e) => {
                const checked = e.target.checked;
                const allValues = TimeFrameArr.map((i) => i.value);
                changeTimeFrame(checked ? allValues : []);
              }}
            >
              全选
            </Checkbox>
          </div>
          <Checkbox.Group
            className={styles.tactic_line_checkbox}
            onChange={changeTimeFrame}
            value={strategyData?.hourOrderList || []}
          >
            <Row>
              {TimeFrameArr.map((i) => (
                <Col span={4} key={i.value}>
                  <Checkbox disabled={disabled} value={i.value} key={i.value}>
                    {i.label}
                  </Checkbox>
                </Col>
              ))}
            </Row>
          </Checkbox.Group>
        </div>
      )}
      <div className={styles.tactic_line_margin}>
        <div className={styles.tactic_line_title}>交易单元</div>
        <DealUnit index={index} strategyData={strategyData} disabled={disabled} />
      </div>
      <div className={styles.table}>
        <div className={styles.tactic_line_margin}>
          <div className={styles.tactic_line_title}>
            限额条件
            <Tooltip title={TOOLTIP_INFO}>
              <QuestionCircleOutlined style={tooltipStyle} />
            </Tooltip>
          </div>
          <Space direction="vertical">
            <div className={styles.tactic_line_radio}>
              <div className={styles.tactic_line_radio_label}>电力</div>
              <Select
                disabled={disabled}
                style={{ width: '100%' }}
                placeholder={'请选择'}
                onChange={changeElectricEnergy}
                value={strategyData.electricEnergy}
              >
                {ELECTRIC_ENERGY_OPTIONS.map((i) => (
                  <Option key={i.value} value={i.value}>
                    {i.label}
                  </Option>
                ))}
              </Select>
            </div>
            <div className={styles.tactic_line_radio}>
              <div className={styles.tactic_line_radio_label}>电价</div>
              <Select
                disabled={disabled}
                style={{ width: '78%', marginRight: '2%' }}
                placeholder={'请选择'}
                value={strategyData.electricPriceType}
                onChange={changeElectricPriceType}
              >
                {ELECTRIC_PRICE_OPTIONS.map((i) => (
                  <Option key={i.value} value={i.value}>
                    {i.label}
                  </Option>
                ))}
              </Select>
              <Input
                style={{ width: '20%' }}
                disabled={disabled || strategyData.electricPriceType !== 3}
                value={strategyData.electricPrice}
                type={'number'}
                onChange={changeElectricPrice}
              />
            </div>
          </Space>
        </div>
        <div className={styles.table_box}>
          {type !== 'intraday' ? (
            <>
              <TjTable
                style={tableStyle}
                useOuterBorder={true}
                stickyScrollHeight={10}
                useVirtual={{ horizontal: true, vertical: true, header: false }}
                defaultColumnWidth={100}
                {...(disabled ? { ...disablePipeline.getProps() } : { ...pipeline.getProps() })}
              />
              {showAddBtn && !disabled && (
                <div className={styles.tactic_line_add} onClick={addTableLine}>
                  <PlusSquareOutlined style={{ marginRight: 5 }} />
                  新增
                </div>
              )}
            </>
          ) : (
            <TjTable
              style={tableStyle}
              useOuterBorder={true}
              stickyScrollHeight={10}
              useVirtual={{ horizontal: true, vertical: true, header: false }}
              defaultColumnWidth={100}
              {...(disabled
                ? { ...treeDisablePipeline.getProps() }
                : { ...treePipeline.getProps() })}
            />
          )}
        </div>
      </div>
    </TacticPage>
  );
};

export default connect(({ global, interprovincialSpotDeclaration }) => ({
  endOrder: interprovincialSpotDeclaration.endOrder,
  planData: interprovincialSpotDeclaration.planData,
  activeKey: interprovincialSpotDeclaration.activeKey,
  date: interprovincialSpotDeclaration.date,
  type: interprovincialSpotDeclaration.type,
  selectRowsObj: interprovincialSpotDeclaration.selectRowsObj,
  hourOrder: interprovincialSpotDeclaration.hourOrder,
}))(Tactic2);
